/* ---------------------------------------------------------------------------
** Serializer.h
** A static template class to marshalling & unmarshalling list<type> data into 
** a byte stream for transmission over a network.
**
** Build Instructions:  Build and launch order have been set in solution properites
** Hit F7 to build solution, then F5 to run it.  Server and client will launch in their
** own separate windows.
**
** Author:	Patrick Montgomery
** Course:	SE 558
** Date:	Oct 6th, 2009
** -------------------------------------------------------------------------*/

#include <list>

using namespace std;

// Static templated class to serialize list structs for transmission over a network
template <typename Type>
class Serializer
{
public:
	~Serializer() {}
	static void marshallList(list<Type>& in, char* out);
	static void unmarshallList(char* in, list<Type>& out);
private:
	Serializer() {}
};

// Put the # of items in the list in the first slot of the buffer, followed
// by the contents of the list.  
template <typename Type>
void Serializer<Type>::marshallList(list<Type>& in, char* out)
{
	Type* tempOut = (Type*)out;
	tempOut[0] = in.size();

	int i=1;
	for (list<Type>::iterator it = in.begin(); it != in.end(); ++it)
	{
		tempOut[i] = *it;
		++i;
	}

	out = (char*)tempOut;
}


// Read the first slot in the list to find the count, then push that many
// elements onto the list
template <typename Type>
void Serializer<Type>::unmarshallList(char* in, list<Type>& out)
{
	out.clear();

	Type* tempIn = (Type*)in;
	int count = (int)tempIn[0];

	for (int i=1; i < count+1; i++)
		out.push_back((Type)tempIn[i]);
}
